<?php

namespace App\Exceptions;

use Exception;
use Dingo\Api\Exception\Handler as DinggoExceptionHander;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Validation\ValidationException;
use Tymon\JWTAuth\Exceptions\JWTException;

class DinggoHandler extends DinggoExceptionHander
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\HttpModelNotFoundException\Response
     */
    public function render($request, Exception $exception)
    {
        $debug = config('app.debug',false);
        if ($debug) {
            $traceData = $exception->getTrace();
            $traceData = getArrayLimit($traceData,5);
        } else {
            $traceData = null;
        }
        $message =  $exception->getMessage();
        $code  = $exception->getCode();

        switch (true) {
            case ($exception instanceof ModelNotFoundException) :
                return returnData($traceData,'模型未查到此数据'.$message, 4004);
                break;
            case ($exception instanceof ApiException):
                return returnData($traceData, $message, $exception->getServiceCode());
                break;
            case ($exception instanceof ValidationException):
                $errors= collect($exception->errors());
                $message = $errors->first()[0];
                return returnData($exception->errors() , $message, 4000 );
                break;
            case ($exception instanceof QueryException): # 数据库失败
                return returnData([
                    $exception->getBindings(),
                    $exception->getSql()
                ] , $message, 4000 );
                break;
        }

        return returnData($traceData, $message, $code);
//        return parent::render($request, $exception);
    }
}
